from os import path
import re
from urllib import request

from api.api_db import insert_file_path
from common.pd import SQL
from project.web_comm import add_token_to_url


# region 文函下载
def contains_illegal_char(filename):
    illegal_chars = ''.join(map(chr, range(32)))
    illegal_chars += '\\/:*?"<>|'
    illegal_chars += ''.join(map(chr, range(127, 256)))
    return any(char in illegal_chars for char in filename)


def remove_illegal_chars(file_name):
    new_filename = re.sub(r'[\/:*?"<>|]', '', file_name)

    return new_filename


def make_file_name_by_id(table_name: str, once_id: str):
    if "doc" in table_name:
        find_data_str = f'select file_name, title from {table_name} where once_id = "{once_id}"'

        sql = SQL()
        data = sql.find_one(find_data_str)
        if data:
            file_name = data[0] + "-" + data[1]
            return remove_illegal_chars(file_name)


def down_load_file(once_id, file_path):
    url = f"http://once/once/docdownload?objectId={once_id}"
    url_str = add_token_to_url(url)

    request.urlretrieve(url_str, file_path)


def download_file_to_save(dir_path, table_name, file_once_id):
    file_name = make_file_name_by_id(table_name, file_once_id)
    file_path = path.join(dir_path, file_name)
    down_load_file(file_once_id, file_path)
    if path.isfile(file_path):
        insert_file_path(file_path, table_name, file_once_id)


# endregion


# region 文函整理
"""
1 获取文件或函件信息
2 查找文件地址列表中是否有
3 根据文函的信息放入对应的文件夹中
"""
def is_doc(file_name):
    pass

# endregion
